package com.ming.stringstudy.feedbacksystem.Interceptor;

import com.ming.stringstudy.feedbacksystem.utils.HeaderName;
import com.ming.stringstudy.feedbacksystem.utils.JwtUtils;
import com.ming.stringstudy.feedbacksystem.utils.PermissionConstants;
import com.ming.stringstudy.feedbacksystem.utils.PermissionUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 为接口注入用户id的拦截器
 */
@Slf4j
@Component
public class UserIdAutowiredInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求url
        String url = request.getRequestURI();
        // 判断请求url是否包含login，如果包含，说明是登录请求，直接放行
        if (url.contains("login")||url.contains("register")) {
            log.info("登录注册操作，不进行注入");
            return true;
        }
        Integer userId = JwtUtils.parserJwt(request.getHeader(HeaderName.headerName)).get("id",Integer.class);
        request.setAttribute("userId", userId);
        return true;
    }
}
